
let lastMessage = {}
      window.addEventListener("keyup", (e) => {
        if (e.keyCode === 13) {
          sendMsg();
        }
      });
      sendBtn.onclick = function () {
        sendMsg();
      };
      function sendMsg() {
        let msg = inputText.value;
        if (msg) {
          let message = {
            nickname:user.nickname,
            avatar:user.avatar,
            text: msg,
            date: new Date().getTime(),
          };
          lastMessage = message;

          let html = ` 
            <div class="message-item msg-right">
              <div class="message-top">
                <div class="message-name">
                  <span>${user.nickname}</span>
                </div>
                <div class="message-avatar">
                  <img src="${user.avatar}" alt="" />
                </div>
              </div>
              <div class="message-bottom">
                <div class="message-text">${msg}</div>
              </div>
            </div>`;

          // 消息要发送到服务器
          request({
            url: "http://192.168.1.110:3000/sendmsg",
            data: message,
          }).then((res) => {
            console.log(res);
            if (res.code == 200) {
                messageListEle.innerHTML += html;
                inputText.value = "";

                main.scrollTop = messageListEle.offsetHeight + 10;
            }
          });
        }
      }

     
      setInterval(() => {
        getMsg();
      }, 1000);
      //请求服务器，获得最新消息
      function getMsg() {
        request({
          url: "http://192.168.1.110:3000/getmsg",
        }).then((res) => {

          if(res.text){


            if(res.date != lastMessage.date){
                lastMessage = res
                let html = `
                    <div class="message-item msg-left">
                    <div class="message-top">
                        <div class="message-avatar">
                        <img src="${res.avatar}" alt="" />
                        </div>
                        <div class="message-name">
                        <span>${res.nickname}</span>
                        </div>
                    </div>
                    <div class="message-bottom">
                        <div class="message-text">${res.text}</div>
                    </div>
                    </div>`
            messageListEle.innerHTML += html;

            // 设置滚动高度
            main.scrollTop = messageListEle.offsetHeight + 10;

            // console.dir(wrapper.scrollTop)
            }
           
          }
          
        });
      }
